import {
  AfterViewInit,
  Component, ElementRef,
  OnInit, Renderer2, ViewChild,
} from '@angular/core';
import { UploadFile } from '@shared/apes/upload';
import { CdkDrag } from '@angular/cdk/drag-drop';
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'apes-preview-dialog',
  templateUrl: './apes-previewDialog.component.html',
})
export class ApesPreviewDialogComponent implements OnInit, AfterViewInit {

  @ViewChild(CdkDrag, { static: false }) cdkDrag: CdkDrag;

  _fileList: UploadFile[] = [];
  previewImage: any;
  current: any = 0;
  imgW: any;
  imgH: any;
  zoom: number = 1;
  rotate: number = 0;
  isLoading: boolean = false;
  idName: any = 'oImg';

  showPoints: boolean = false;

  constructor(
    // private svgPan: svgPanService,
    protected elementRef: ElementRef,
    private http: HttpClient,
    private renderer: Renderer2,
  ) {
  }

  ngOnInit() {
    // console.log(this._fileList);
    this._fileList.forEach((file) => {
      if (!file.url && file.id) {
        file.url = 'fileserver/view/' + file.id;
      }
      if (file.hasOwnProperty('tifSrc')) {
        if (!/\.TIF$/.test(file.tifSrc) && !/\.tif$/.test(file.tifSrc)) return;
        this.http.request('GET', file.tifSrc, {
          responseType: 'arraybuffer',
        }).subscribe(response => {
          let tiff = new Tiff({ buffer: response });
          file.url = tiff.toDataURL();
        });
      }
      if (file.hasOwnProperty('points')) {
        this.showPoints = true;
      }

    });
    this.previewImage = this._fileList[0];
    this.initImg();
  }

  ngAfterViewInit() {
    // this.svgPan.init(this.nImg.nativeElement);
  }

  initImg() {
    this.isLoading = true;
    setTimeout(() => {
      let img = document.getElementById(this.idName);
      this.loadImg(img, (res) => {
        // console.log(res);
        this.imgW = res.w;
        this.imgH = res.h;
        this.isLoading = false;
        this.reset();
      });
    }, 500);
  }

  get fileList(): UploadFile[] {
    return this._fileList || [];
  }

  set fileList(input: UploadFile[]) {
    let value = input;
    if (this._fileList === value) {
      return;
    }
    this._fileList = value;
  }

  clickThumbnail(i) {
    this.previewImage = this._fileList[i];
    this.current = i;
    this.initImg();
  }

  loadImg(oImg, callback) {
    let nWidth;
    let nHeight;
    if (!oImg.naturalWidth) { // 现代浏览器

      nWidth = oImg.naturalWidth;
      nHeight = oImg.naturalHeight;
      callback({ w: nWidth, h: nHeight });

    } else { // IE6/7/8
      let nImg = new Image();

      nImg.onload = () => {
        let nWidth = nImg.width;
        let nHeight = nImg.height;
        callback({ w: nWidth, h: nHeight });
      };
      nImg.src = oImg.src;
    }
  }

  extractTransformValues(str) {
    const regex = /\(([^)]+)\)/;
    const match = str.match(regex);
    let item = [];
    if (match) {
      item = match[1].split(',').map(value => value.trim());
    }
    return item;
  }


  zoomOut() {
    this.zoom += 0.3;
    if (this.zoom >= 5) {
      this.zoom = 5;
    }

    this.move();
  }

  zoomIn() {
    this.zoom -= 0.3;
    if (this.zoom <= 0.3) {
      this.zoom = 0.3;
    }
    this.move();
  }

  dragStart() {
    this.move();
  }


  rotation() {
    this.rotate = this.rotate + 90;
    let _img = document.querySelector('#oImg');
    this.renderer.setStyle(_img, 'transform', `rotate(${this.rotate}deg)`);
  }

  reset() {
    let _body = document.querySelector('.preview-dialog-content');
    this.cdkDrag.reset();
    if (this.showPoints) {
      this.zoom = Math.floor((_body.clientWidth / this.imgW) * 100) / 100;
    } else {
      this.zoom = 1;
      this.rotate = 0;
      let _img = document.querySelector('#oImg');
      this.renderer.setStyle(_img, 'transform', `rotate(${this.rotate}deg)`);
    }
    this.move();
  }

  move(){
    const pos = this.cdkDrag.getFreeDragPosition();
    this.cdkDrag.getRootElement().style.transform = `translate3d(${pos.x}px, ${pos.y}px, 0px) scale(${this.zoom})`;
  }
}

